using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using System.Threading;

public static class AnimatorUtil
{
    public static async Task TrySetStateAndWaitAsync(GameObject go, string name, int layerIndex = 0)
    {
        var hasState = HasState(go, name);
        if(!hasState)
        {
            return;
        }
        SetState(go, name);
        await WaitUtilNotInStateAsync(go, name, layerIndex);
    }

    public static async Task WaitUtilNotInStateAsync(GameObject go, string name, int layerIndex = 0)
    {
        var animator = go.GetComponent<Animator>();
        if(animator == null)
        {
            return;
        }
        while (true)
        {
            var currentInfo = animator.GetCurrentAnimatorStateInfo(layerIndex);
            var nextInfo = animator.GetNextAnimatorStateInfo(layerIndex);
            var currentIsTarget = currentInfo.IsName(name);
            var nextIfTarget = nextInfo.IsName(name);
            if(!currentIsTarget && !nextIfTarget)
            {
                return;
            }
            if (currentIsTarget)
            {
                if (currentInfo.normalizedTime >= 1f)
                {
                    return;
                }
            }
            await Task.Delay(10);
            if (animator == null)
            {
                return;
            }
        }
    } 

    public static bool HasState(GameObject obj, string stateName)
    {
        var animator = obj.GetComponent<Animator>();
        if(animator == null)
        {
            return false;
        }
        var stateId = Animator.StringToHash(stateName);
        var b = animator.HasState(0, stateId);
        return b;
    }

    public static void SetState(GameObject go, string stateName)
    {
        var animator = go.GetComponent<Animator>();
        if (animator != null)
        {
            animator.CrossFade(stateName, 0f);
            animator.Update(0f);
            animator.Update(0f);
        }
    }

    public static void ResetToDefaultState(GameObject go)
    {
        var animator = go.GetComponent<Animator>();
        if(animator != null)
        {
            animator.CrossFade("Default", 0f);
            animator.Update(0f);
            animator.Update(0f);
        }
    }
}
